<!--  -->
<template>
<div class="content"  :class="className">
  <div v-html="css"></div>
  <div class="commodity-page">
    <div class="commodity-list" v-if="goodsList.length > 0">
      <div class="commodity-items" v-for="(item, index) in goodsList" :key="index" @click="commodityNav(item.id)">
        <div class="container flex">
          <div class="image">
            <img :src="item.thumb" />
            <div class="img-footer flex-j-sb flex-a-c">
              <div class="flex">
                <div class="distance" v-if="locationMore && item.distance != 0">
                  <span class="iconfont icon-service_n"></span>
                  <span>{{ item.distance | kmUnit }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="img-right flex">
            <div class="title">
              {{ item.title }}
            </div>
            <p class="address">{{item.has_one_yz_travel_around_shop_address && item.has_one_yz_travel_around_shop_address.name}}</p>
            <div class="price-item flex-j-sb">
              <div class="pirce flex">
                <div class="pirce-const flex">
                  <span>￥</span>
                  <p>{{ item.price }}</p>
                </div>
                <div class="counter-price flex">
                  <span>￥</span>
                  <p>{{ item.market_price }}</p>
                </div>
              </div>
              <div class="sales">销量{{ item.show_sales }}</div>
            </div>
          </div>
        </div>
        <div class="footer-comm flex-a-c">
            <div>
              <span class="goods-desc ell">
                <span class="time-end" v-if="computingTime(presentTime, item.endTime)">活动结束</span>
                <div  v-else-if="points(item.endTime)" style="display: inline-block;">
                  <div  class="time-end">
                    <van-count-down :time="beforeDay(item.endTime)" format="HH 时 mm 分 ss 秒" />
                  </div>
                  <div style="display: inline-block;">
                    <div class="time-end">即将下架</div>
                  </div>
                </div>
                <span class="panic" v-else>抢购中</span>
                <span class="long-title">{{item.long_title}}</span>
              </span>
            </div>
        </div>
      </div>
    </div>
    <van-empty description="空空如也" v-else-if="goodsFlag && goodsList.length === 0" />
    <van-empty description="加载中" v-else />
    <div class="loadMore" v-if="isLoadMore" @click="getMoreData">加载更多</div>
    <!-- <div class="loadMore" v-if="isLoadMoreSet" @click="getMoreDataAll">加载更多</div> -->
    <div class="loadMore" v-if="lastIndex == index && (page >= total_page)">{{ $i18n.t("没有更多了") }}~~</div>
  </div>
</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
// 自定义样式
const css = function() {
  if (this.datas.preview_color) {
    // 确保数据已传入
    let datas = this.plugin_active && this.openTemplate == 1 ? this.datas_style02 : this.datas;
    const { preview_color, current_price_color, long_title_color,shop_name_color,shop_title_color } = datas;

    return `
        .component-${this.id} .commodity-page {
            background: ${preview_color};
        }
        .component-${this.id} .commodity-list .commodity-items  .container .img-right .title{
            color:${shop_title_color}
        }
        .component-${this.id}  .commodity-list .commodity-items  .container .img-right .address{
            color:${shop_name_color}
        }
        .component-${this.id} .commodity-list .commodity-items .container .img-right .price-item .pirce .pirce-const{
            color:${current_price_color}
        }
        .component-${this.id} .commodity-items .long-title{
            color:${long_title_color}
        }
    `;
  }
};
export default {
  name:'',
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: ["id","page_id", "datas","lastIndex","index","component_key","isBottom","tabcontrol", "isLast"],
  data() {
  return {
    arrIndex: 1, //组件加载下一页
    per_page:15, //每页多少条数据
    isLoadMore: false,
    goodsFlag:false,
    isLoadMoreSet:false,
    allLoaded: false, //全部数据加载完成
    total_page:0,
    locationMore:true,
    presentTime: "",
    point: {},
    query: {
      //筛选商品的
      page: 1,
      longitude: "",
      latitude: "",
      city: "",
      cityCode: ""
    },
    goodsList:[],
    travelUnList:[]
  };
  },
  filters: {
    kmUnit(value) {
      let val = parseInt(value);
      let v;
      if (typeof val === "number" && !isNaN(val)) {
        if (val >= 1000) {
          v = (val / 1000).toFixed(2) + "km";
        } else {
          v = val + "m";
        }
      } else {
        v = "0m";
      }
      return v;
    }
  },
  //监听属性 类似于data概念
  computed: {
    css() {
      return "<style>" + css.call(this) + "</style>";
    },
    className() {
      const name = ["component-wrapper", `component-${this.id}`];
      return name;
    }
  },
  //监控data中的数据变化
  watch: {
    isBottom: function(newVal, oldVal) {
      if (this.tabcontrol) {
        // 选项卡this.isLast判断商品列表是最后一个组件
        if (newVal && this.isLast && this.isLoadMore) {
          this.getMoreData();
        }
      }
      // this.lastIndex == this.index判断商品列表是最后一个组件
      if (newVal && this.lastIndex == this.index && this.isLoadMore) {
        this.getMoreData();
      } 
    }
  },
  //方法集合
  methods: {
    computingTime(afterTime, backTime) {
      //判断是否活动结束
      if (!Number(backTime)) return;
      let res = Number(afterTime) - Number(backTime);
      if (res === 0) {
        return true;
      }
      if (res > 0) {
        return true;
      } else {
        return false;
      }
    },
    commodityNav(id) {
      this.$router.push(this.fun.getUrl("tourAroundGoodsDetails", {}, { goodsId: id,latitude: this.query.latitude ,longitude:this.query.longitude}));
    },
    beforeDay(time) {
      //结束时间减去前一天
      return time - Number(this.presentTime);
    },
    points(backTime) {
      //判断是否到最后一天了
      let TimeDate = new Date(Number(backTime));
      let disposeTime = new Date(new Date(TimeDate).toLocaleDateString()).getTime();
      var date1 = new Date(new Date().toLocaleDateString()).getTime();
      return date1 === Number(disposeTime) ? true : false;
    },
    timestampToTime(timestamp) {
      if (!timestamp) return;
      var date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "/";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "/";
      let D = this.change(date.getDate()) + " ";
      let h = this.change(date.getHours()) + ":";
      let m = this.change(date.getMinutes());
      return Y + M + D + h + m;
    },
    setListData() { //处理列表数据是自动获取还是手动获取
      if(this.datas?.list?.data) {
        this.total_page = this.datas.list.last_page;
        if(this.total_page <= this.query.page) {
          this.isLoadMore = false;
        }
        if(this.goodsList.length > this.datas.get_number) { //大于后台控制的数量就显示后台数量列表
          this.goodsList.splice(this.datas.get_number,this.goodsList.length-this.datas.get_number);
          this.isLoadMore = false;
        }
      }else {
        if(this.datas.list.length <= 0) {
          this.isLoadMore = false;
        }
      }
      if(this.datas.get_style == "2") {
        this.isLoadMore = false;
      }
    },
    getGoodsList(isLocation) {
      if (this.query.latitude === "" && this.query.longitude === "") {
        this.locationMore = false;
      } else {
        this.locationMore = true;
      }
      this.goodsFlag = false;
      let json = {
        decorate_id: this.page_id || this.$store.state.temp.item.id,
        component_id: this.id,
        component_key: 'U_travelAround',
        ...this.query
      }
      $http
        .post(
          "home-page.get-decorate-page",
          json,'loading')
        .then((response)=> {
          this.isLoadMore = true;
          if (response.result === 1) {
            let res = response.data;
            let list = res?.data;
            this.goodsList = [].slice.call(list) || [];//后端返回的类型是数组对象需要转化
            this.total_page = res?.last_page;
            this.goodsFlag = true;
            if(this.page >= this.total_page) {
              this.isLoadMore = false;
            }
            if(this.datas.get_style == "2") {
              this.isLoadMore = false;
            }
            if(this.datas.get_style == "1") { //装修自动获取
              if(this.goodsList.length > this.datas.get_number) {
                this.goodsList.splice(this.datas.get_number, this.goodsList.length-this.datas.get_number);
                this.isLoadMore = false;
              }
            }
            if(isLocation) {
              this.locationFun();
            }
          } else {
            this.query.page = this.query.page - 1;
            this.isLoadMore = false;
          }
        },
        function(response) {
          console.error(response);
          // error callback
        });
    },
    locationFun() {
      this.page = 1;
      this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.query.latitude = p.lat;
        this.query.longitude = p.lng;
        let adcode = res.addressComponent.adcode;
        let interceptionCity = adcode.toString().slice(0, 4) + "00";
        this.query.cityCode = interceptionCity;
        // this.query.city = (res.addressComponent.city).trim();
        this.query.page = 1;
        this.goodsFlag = false;
        this.getGoodsList();
      })
      .catch(err => {
        this.goodsFlag = false;
        this.getGoodsList();
      })
    },
    // 获取更多数据
    getMoreData() {
      this.isLoadMore = false;
      if (this.query.page >= this.total_page) {
        return;
      } else {
        this.query.page = this.query.page + 1;
        let json = {
          decorate_id: this.page_id || this.$store.state.temp.item.id,
          component_id: this.id,
          component_key: 'U_travelAround',
          ...this.query
        }
        $http
        .post(
          "home-page.get-decorate-page",
          json,'loading')
        .then((response)=> {
          this.isLoadMore = true;
          if (response.result === 1) {
            let res = response.data;
            let list = [].slice.call(res?.data) || [];;
            this.goodsList = this.goodsList.concat(list);;//数组拼接
            this.goodsFlag = true;
            if(this.datas.get_style == "1") { //装修自动获取
              if(this.goodsList.length > this.datas.get_number) {
                this.goodsList.splice(this.datas.get_number, this.goodsList.length-this.datas.get_number);
                this.isLoadMore = false;
              }
            }
            if(this.query.page >= this.total_page) {
              this.isLoadMore = false;
            }
          } else {
            this.query.page = this.query.page - 1;
            this.isLoadMore = false;
          }
        },
        function(response) {
          console.error(response);
          // error callback
        });
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.presentTime = new Date().getTime();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    console.log(this.datas.get_style);
    let myLocation = this.$store.state.o2oLocation;//获取缓存定位信息
    if(!myLocation.point) {
      this.getGoodsList(true);
    } else {
      let point = myLocation.point;
      this.query.latitude = point.lat;
      this.query.longitude = point.lng;
      let adcode = myLocation.addressComponent?.adcode;
      let interceptionCity = adcode.toString().slice(0, 4) + "00";
      // this.query.city = myLocation.city;
      this.query.cityCode = interceptionCity;
      this.query.page = 1;
      this.getGoodsList();
    }
    this.setListData();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
.commodity-items ::v-deep .van-count-down {
  color: #fff;
  font-size: 0.625rem;
  line-height: 0.625rem;
}
</style>
<style scoped lang="scss">
/* @import url(); 引入公共css类 */
.loadMore {
  width: 100%;
  height: 50px;
  cursor: pointer;
  line-height: 50px;
  text-align: center;
  clear: both;
}
.commodity-list {
    padding:0.625rem 0.625rem 0 0.625rem;
    .commodity-items {
      background-color: #fff;
      border-radius: 0.3125rem;
      margin-bottom: 0.625rem;
      padding: 0.8125rem;
      &:last-child {
        margin-bottom:0;
      }

      .container {
        .image {
          width: 9.375rem;
          // height: 4.6875rem;
          background: #bfbaba;
          border-radius: 0.125rem;
          position: relative;

          .img-footer {
            width: 100%;
            box-sizing: border-box;
            justify-content: flex-end;
            position: absolute;
            bottom: 0;
            right: 0;
            padding: 0 0.3125rem 0.25rem 0;

            .distance {
              border-radius: 0.625rem 0.625rem 0.625rem 0.625rem;
              padding: 0.3125rem 0.4375rem;
              background-color: rgba(0, 0, 0, 0.5);
              color: #fff;
              font-size: 0.625rem;
              line-height: 0.625rem;

              .icon-service_n {
                padding-right: 0.25rem;
                font-size: 0.875rem;
              }
            }
          }

          img {
            width: 9.375rem;
            height: 100%;
            // height: 4.6875rem;
            border-radius: 0.125rem;
          }
        }

        .img-right {
          padding: 0  0 0 0.625rem;
          flex-direction: column;

          .title {
            font-size: 0.875rem;
            font-weight: bold;
            color: #2c2c2c;
            text-align: left;
            padding: 0  0 0.625rem 0;
          }

          .address {
            text-align: left;
            font-size: 12px;
            color: #313131;
            padding-bottom: 14px;
          }

          .price-item {
            align-items: center;

            .pirce {
              .pirce-const {
                padding: 0 10px 0 0;
                color: #f10000;
                font-size: 1rem;
                line-height: 1rem;
                align-items: flex-end;

                span {
                  font-size: 0.625rem;
                }
              }

              .counter-price {
                font-size: 0.6875rem;
                text-decoration: line-through;
                color: #929292;
              }
            }
          }

          .sales {
            font-size: 0.6875rem;
            line-height: 0.6875rem;
            font-weight: 400;
            color: #929292;
          }
        }
      }

      .footer-comm {
        text-align: left;
        padding: 0.6875rem 0 0 0;

        .goods-desc {
          font-size: 0.6875rem;
          font-weight: 400;
          color: #313131;
          text-align: left;
          // padding-left: 10px;
        }

        .time-end {
          line-height: 0.625rem;
          padding: 0.375rem 0.375rem 0.3125rem 0.4375rem;
          background: #f10000;
          color: #fff;
          border-radius: 0.625rem 0.625rem 0.625rem 0.625rem;
          display: inline-block;
        }

        .time-end:last-child {
          margin-left: 0.3125rem;
          color: #fff;
          display: inline-block;
        }

        .panic {
          font-size: 10px;
          line-height: 10px;
          padding: 4px 7px;
          display: inline-block;
          color: #fff;
          border-radius: 2px 2px 2px 2px;
          background-color: #11c9a4;
          margin-right: 8px;
        }

        .panic-space {
          width: 10px;
          display: inline-block;
          clear: both;
        }
      }
      
    }
  }
</style>